package cn.tedu._05article.controller;

import cn.tedu._05article.base.response.JsonResult;
import cn.tedu._05article.base.response.StatusCode;
import cn.tedu._05article.mapper.UserMapper;
import cn.tedu._05article.pojo.dto.UserArticleParam;
import cn.tedu._05article.pojo.dto.UserLoginParam;
import cn.tedu._05article.pojo.entiy.Article;
import cn.tedu._05article.pojo.vo.ArticleVO;
import cn.tedu._05article.pojo.vo.UserVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
@Validated
@Tag(name="用户模块")
@Slf4j
@RestController
@RequestMapping("/v1/user/")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @PostMapping("login")
    @Operation(summary = "用户登录")
    @ApiOperationSupport(order = 10)
    public JsonResult login(@RequestBody UserLoginParam userLoginParam, HttpSession session){
        log.debug("userLoginParam = "+userLoginParam);
        UserVO userVO=
                userMapper.selectByUsernameAndPassword(userLoginParam);
        if(userVO==null){
            return new JsonResult(StatusCode.OPERATION_FAILED);
        }
        session.setAttribute("user",userVO);
        log.debug("userVO = "+userVO);
        return JsonResult.ok(userVO);

    }


    @PostMapping("article")
    @Operation(summary = "发表文章")
    @ApiOperationSupport(order = 20)
    public JsonResult article(@Validated @RequestBody UserArticleParam userArticleParam ,
                              HttpSession session){
        log.debug("userArticleParam = "+userArticleParam);
        UserVO userVO= (UserVO) session.getAttribute("user");
//        if (userVO==null){
//            return new JsonResult(StatusCode.NOT_LOGIN);
//        }
        Article article = new Article();
        BeanUtils.copyProperties(userArticleParam,article);
        article.setUserId(userVO.getId());
        userMapper.insertArticle(article);
        return JsonResult.ok();
    }
    /**
     * 查询文章
     */
    @GetMapping("selectByArticleId")
    @Operation(summary = "查询文章")
    @ApiOperationSupport(order = 30)
    public JsonResult selectByArticleId(@Range(min = 1,max = 100,message = "文章ID要在1-100之间") Long id){

        ArticleVO articleVO=userMapper.selectByArticleId(id);
        log.debug("id = "+id);
        return JsonResult.ok(articleVO);
    }

}
